package edu.biwu.advice;

import edu.biwu.utils.TransactionManager;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Log4j2
@Aspect
public class TransactionAdvice {
    @Autowired
    private TransactionManager transactionManager;
    @Around("execution(* edu.biwu.service..*.*(..))" +
            "&& !execution(* edu.biwu.service..*.find*(..))")
    public Object aroundServiceAdvice(ProceedingJoinPoint pjp){
        Object retVal = null;
        try {
            transactionManager.beginTransaction();
            log.info("开启事务");
            log.info("执行{}目标方法"+pjp.getSignature());
            retVal = pjp.proceed();
            transactionManager.commitTansaction();
            log.info("提交事务");
        } catch (Throwable e) {
            transactionManager.rollbackTransaction();
            log.info("回滚事务");
            throw new RuntimeException(e);
        } finally {
            transactionManager.releaseConnection();
            log.info("释放资源");
        }
        return retVal;
    }
}
